//
//  DemandTheHallContentVC.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/11/16.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "DemandTheHallContentVC.h"
#import "DemandTheHallContentHeadView.h"
#import "DemandTheHallContentHeadCell.h"
#import "HomeServiceDetailsIntroductionContentTwoCell.h"
#import "WriteRequirementCollectionCell.h"
#import "HomeModel.h"
#import "WriteRequirementTitleCell.h"
#import "DemandCell.h"
#import "ButtonCell.h"
#import "TextFieldCell.h"
#import "CellFrameModel.h"
#import "ContentCell.h"
#import "ArrowheadMenu.h"// 箭头菜单
#import "WriteRequirementTabVC.h"
#import "DemandTheHallViewController.h"
#define kSectionHeight 40
@interface DemandTheHallContentVC ()<UITableViewDelegate,UITableViewDataSource,ButtonCellDelegate,DemandCellDelegate,UIScrollViewDelegate,DemandTheHallContentHeadCellDelegate,MenuViewControllerDelegate>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) DemandTheHallContentHeadView *headView;
@property(nonatomic,strong) NSString *pageNumber;
@property(nonatomic,strong) NSString *pageSize;
@property(nonatomic,strong) NSString *IndustryIds;
@property(nonatomic,strong) NSMutableArray *demandArray;
@property(nonatomic,strong) NSDictionary *dict;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong) NSString *stringUrl;
@property(nonatomic,strong) UIView *sectionHeadView;
@property(nonatomic,strong) UIButton *btn;
@property(nonatomic,strong) NSMutableArray *dataMuta;
@property(nonatomic,strong) NSIndexPath *indexPath;
@property(nonatomic,strong) UIButton *checkBtn;
@property(nonatomic,assign) BOOL collectDemand;
@property(nonatomic,strong) UIButton *contaceBtn;
@property (nonatomic, strong)NSArray *array;
@property (nonatomic, assign)CGFloat sumHeight;
@property(nonatomic,strong) NSMutableArray *complainMuta;
@property(nonatomic,assign) NSInteger tag;
@property(nonatomic,strong) ArrowheadMenu *menuVC;
@end
static NSString *identifierWriteRequirementCollectionCell = @"WriteRequirementCollectionCell";
static NSString *identifierWriteRequirementTitleCell = @"WriteRequirementTitleCell";
static NSString *identifierDemandCell = @"DemandCell";
static NSString *identifierButtonCell = @"ButtonCell";
static NSString *identifierCellHead = @"DemandTheHallContentHeadCell";
static NSString *identifierHomeServiceDetailsIntroductionContentTwoCell = @"HomeServiceDetailsIntroductionContentTwoCell";
static NSString *identifierContent = @"contentCell";
static NSString *identifierCell = @"Cell";
@implementation DemandTheHallContentVC
-(NSMutableArray *)complainMuta
{
    if (!_complainMuta) {
        
        NSArray *pathFile = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *complain = @"";
        NSArray *temp = nil;
        complain = [pathFile[0] stringByAppendingPathComponent:@"complainMuta.plist"];
        temp = [NSArray arrayWithContentsOfFile:complain];
        if (temp.count) {
            _complainMuta = [NSMutableArray arrayWithArray:temp];
        }else {
            _complainMuta = [NSMutableArray array];
        }

    }
    return _complainMuta;

}
-(NSArray *)array
{
    if (!_array) {
        _array = @[@"投诉"];
    }
    return _array;
}
-(NSMutableArray *)dataMuta
{
    if (!_dataMuta) {
        _dataMuta = [NSMutableArray array];
    }
    return _dataMuta;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, kVHeight-kNavAndStatusHight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
//        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
-(NSMutableArray *)demandArray
{
    if (!_demandArray) {
        _demandArray = [NSMutableArray array];
    }
    return _demandArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"需求详情";
    self.manager = [AFHTTPSessionManager manager];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"icon_111"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(clickRightItem:)];
    [self.view addSubview:self.tableView];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WriteRequirementTitleCell" bundle:nil] forCellReuseIdentifier:identifierWriteRequirementTitleCell];
    [self.tableView registerClass:[WriteRequirementCollectionCell class] forCellReuseIdentifier:identifierWriteRequirementCollectionCell];
    [self.tableView registerClass:[HomeServiceDetailsIntroductionContentTwoCell class] forCellReuseIdentifier:identifierHomeServiceDetailsIntroductionContentTwoCell];
    [self.tableView registerClass:[ContentCell class] forCellReuseIdentifier:identifierContent];
    [self.tableView registerNib:[UINib nibWithNibName:@"ButtonCell" bundle:nil] forCellReuseIdentifier:identifierButtonCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DemandCell" bundle:nil] forCellReuseIdentifier:identifierDemandCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"DemandTheHallContentHeadCell" bundle:nil] forCellReuseIdentifier:identifierCellHead];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectDemandByIds:) name:@"selectDemandByIds" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenDemandTheHall:) name:@"checkTokenDemandTheHall" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkTokenError:) name:@"checkTokenError" object:nil];
    self.headView.model = self.homeModel;
    
    self.tableView.tableHeaderView = self.headView;
    //    self.tableView.backgroundColor = kOrangeBg;
    XLog(@"需求概括:%@",self.homeModel.represent);
    self.pageNumber =@"1";
    self.pageSize =@"10";
    self.IndustryIds = @"1";
    [self relaodInternetData];
    self.sectionHeadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kVWidth, kSectionHeight)];
    [self.view addSubview:self.sectionHeadView];
    self.sectionHeadView.backgroundColor = [UIColor whiteColor];
    for (int i = 0; i < 2; i++) {
        self.btn = [[UIButton alloc]initWithFrame:CGRectMake(kVWidth/2*i, 0, kVWidth/2, kSectionHeight)];
        [self.sectionHeadView addSubview:self.btn];
        [self.btn addTarget: self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
        NSArray *titles = @[@"详情介绍",@"推荐"];
        [self.btn setTitle:titles[i] forState:UIControlStateNormal];
        self.btn.tag = i;
        if (i == 0) {
            [self.btn setTitleColor:kOrangeBg forState:UIControlStateNormal];
            self.btn.titleLabel.font = [UIFont systemFontOfSize:16];
        }else {
            [self.btn setTitleColor:kLabel153Color forState:UIControlStateNormal];
            self.btn.titleLabel.font = [UIFont systemFontOfSize:14];
        }
    }
    CGFloat statusHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
    CGFloat navHeight = self.navigationController.navigationBar.frame.size.height;
    
    self.sumHeight = statusHeight + navHeight;
    self.sectionHeadView.hidden = YES;
    self.contaceBtn = [[UIButton alloc]initWithFrame:CGRectMake(kUIScreen.size.width*0.1, kUIScreen.size.height*0.82, kUIScreen.size.width*0.8, 44)];
    [self.view addSubview:self.contaceBtn];
    [self.contaceBtn setBackgroundColor:kOrangeBg];
    self.contaceBtn.layer.masksToBounds = YES;
    self.contaceBtn.layer.cornerRadius = 6;
    self.contaceBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.contaceBtn addTarget: self action:@selector(contactBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.contaceBtn setTitle:@"立即联系" forState:UIControlStateNormal];
//    UIMenuController *menu = [UIMenuController alloc]init
}
#pragma mark-投诉
-(void)clickRightItem:(UIBarButtonItem *)sender
{
    NSArray *pathFile = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *complain = @"";
    complain = [pathFile[0] stringByAppendingPathComponent:@"complainMuta.plist"];
    NSString *message = @"";
    if (self.complainMuta.count) {
        if (![self.complainMuta containsObject:[NumberSwitchString numberSwitchString:self.homeModel.id]]) {
            message = @"投诉";
        }else {
            message = @"已投诉";
        }
    }else {
        message = @"投诉";
    }
    self.menuVC = [[ArrowheadMenu alloc] initDefaultArrowheadMenuWithTitle:@[message,@"新建需求"] icon:@[@"tousu",@"new_tianjia"] menuPlacements:ShowAtBottom ];
    self.menuVC.delegate = self;
    [self.menuVC presentMenuView:sender];
    XLog(@"NSHomeDirectory():%@",NSHomeDirectory());
}
// 菜单代理方法
- (void)menu:(BaseMenuViewController *)menu didClickedItemUnitWithTag:(NSInteger)tag andItemUnitTitle:(NSString *)title {
    [menu dismissViewControllerAnimated:NO completion:^{
        if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
            [LogOutAccount presentOutAccount];
            [UIAlertViewWarningAccount showWarningAccount];
        }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
            [LogOutAccount presentOutAccount];
        }else {
            self.tag = tag;
            self.dict = @{
                          @"userId":[UserDefaultsHelper readUid],
                          @"token":[UserDefaultsHelper readToken]
                          };
            self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
            [CustomeManager POSTCheckTokenWithURLIndex:4 parameters:self.dict success:^(NSDictionary *dict) {
                
            } failure:^(NSError *error) {
                
            }];
        }
    }];
}
#pragma mark-代理:checkToken
-(void)checkTokenDemandTheHall:(NSNotification *)info
{
    if (self.tag == 0) {
        NSArray *pathFile = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *complain = @"";
        complain = [pathFile[0] stringByAppendingPathComponent:@"complainMuta.plist"];
        NSArray *temp = [NSArray array];
        temp = [NSArray arrayWithContentsOfFile:complain];
        if (temp.count) {
            self.complainMuta = [NSMutableArray arrayWithArray:temp];
        }else {
            self.complainMuta = [NSMutableArray array];
        }
        if (self.complainMuta.count) {
            if (![self.complainMuta containsObject:[NumberSwitchString numberSwitchString:self.homeModel.id]]) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"投诉成功"];
                [self.complainMuta addObject:[NumberSwitchString numberSwitchString:self.homeModel.id]];
                [self.complainMuta writeToFile:complain atomically:YES];
            }else {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"不可重复投诉"];
            }
        }else {
            [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"投诉成功"];
            [self.complainMuta addObject:[NumberSwitchString numberSwitchString:self.homeModel.id]];
            [self.complainMuta writeToFile:complain atomically:YES];
        }
    }else {
        WriteRequirementTabVC *vc = [[WriteRequirementTabVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
        
}
-(void)checkTokenError:(NSNotification *)info
{
//    [UIAlertViewWarningAccount showWarningAccount];
//    [LogOutAccount presentOutAccount];
}

#pragma mark-收藏
- (void)demandTheHallContentHeadCell:(DemandTheHallContentHeadCell *)demandTheHallContentHeadCell withCollectBtn:(UIButton *)collectBtn
{
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                collectBtn.selected = !collectBtn.selected;
                NSString *ids = [NSString stringWithFormat:@"%ld",self.homeModel.id];
                NSString *status = [NSString stringWithFormat:@"%d",collectBtn.selected];
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"id":ids,
                              @"type":@"1",
                              @"status":status,
                              @"token":[UserDefaultsHelper readToken]
                              };
                XLog(@"self.dict:%@",self.dict);
                self.urlString = [NSString stringWithFormat:@"%@/collection/insertCollection",kUrl];
                [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    NSString *message = [responseObject objectForKey:@"message"];
                    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
                    //FunctionVC刷新收藏
                    if (self.returnValueBlock) {
                        self.returnValueBlock(collectBtn.selected);
                    };
                    /**
                     收藏,取消收藏,给所有界面发送通知,刷新收藏按钮
                     */
                        if (![self.navigationController.viewControllers[0] isKindOfClass:[DemandTheHallViewController class]]) {
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                XLog(@"self.navigationController.viewControllers[0]:%@",self.navigationController.viewControllers[0]);
                                NSNotification *notification = [NSNotification notificationWithName:@"collectDemandContent" object:nil];
                                [[NSNotificationCenter defaultCenter]postNotification:notification];
                            });
                        }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }else {
                [UIAlertViewWarningAccount showWarningAccount];
                [LogOutAccount presentOutAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
    
}
-(void)clickCollect:(UIButton *)collectBtn
{
    
}
- (void)setId:(NSInteger)id
{
    _id = id;
    [self reloadInternetIDSData];
}
-(void)reloadInternetIDSData
{
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    self.dataMuta = nil;
    NSString *ids = [NSString stringWithFormat:@"%ld",self.id];
    self.dict = @{
                  @"ids":ids
                  };
    [CustomeManager POSTWithURLIndex:21 parameters:self.dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)selectDemandByIds:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *temp = [dict objectForKey:@"date"];
    if (![temp isKindOfClass:[NSNull class]]) {
        for (NSDictionary *dict in temp) {
            HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
//            [self.dataMuta addObject:model];
            self.homeModel = model;
        }
        [self.tableView reloadData];
        [WSProgressHUD dismiss];
    }
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)clickBtn:(UIButton *)clickBtn
{
    if (clickBtn.tag == 0) {
        for (id obj in self.sectionHeadView.subviews) {
            if ([obj isKindOfClass:[UIButton class]]) {
                XLog(@"obj:%@",obj);
                UIButton *btn = (UIButton *)obj;
                if (btn.tag == 0) {
                    [btn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                    btn.titleLabel.font = [UIFont systemFontOfSize:16];
                }else{
                    [btn setTitleColor:kLabel153Color forState:UIControlStateNormal];
                    btn.titleLabel.font = [UIFont systemFontOfSize:14];
                }
            }
        }
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
      
    }else {
        for (id obj in self.sectionHeadView.subviews) {
            if ([obj isKindOfClass:[UIButton class]]) {
                XLog(@"obj:%@",obj);
                UIButton *btn = (UIButton *)obj;
                if (btn.tag == 0) {
                    [btn setTitleColor:kLabel153Color forState:UIControlStateNormal];
                    btn.titleLabel.font = [UIFont systemFontOfSize:14];
                }else{
                    [btn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                    btn.titleLabel.font = [UIFont systemFontOfSize:16];
                }
            }
        }
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:2];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
//        self.tableView scroll
    }
}

-(void)relaodInternetData
{
//    NSString *demandId = [NSString stringWithFormat:@"%ld",self.homeModel.id];
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];

    XLog(@"self.homeModel.industry:%@",self.homeModel.industry);
    self.dict = @{
                  @"pageNum":self.pageNumber,
                  @"pageSize":self.pageSize,
                  @"industry":self.homeModel.industry,
                  @"uid":[UserDefaultsHelper readUid],
                  @"token":[UserDefaultsHelper readToken]
                  };
    XLog(@"相似需求self.dict:%@",self.dict);
    self.stringUrl = [NSString stringWithFormat:@"%@/demand/selectDemandByIndustryId;",kUrl];
    XLog(@"self.stringUrl:%@",self.stringUrl);
    [self.manager POST:self.stringUrl parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        XLog(@"DemandTheHallContentVC:%@",responseObject);
        NSArray *temp = [responseObject objectForKey:@"date"];
        for (NSDictionary *dict in temp) {
            HomeModel *model =[HomeModel mj_objectWithKeyValues:dict];
            [self.demandArray addObject:model];
        }
        [self.tableView reloadData];
        [WSProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        XLog(@"error:%@",error);
    }];
    
    
    

}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:2];
    HomeServiceDetailsIntroductionContentTwoCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    CGFloat scrollY = CGRectGetMaxY(cell.frame)-kSectionHeight;
    XLog(@"scrollView.contentOffset.y:%f",scrollView.contentOffset.y);
    XLog(@"scrollY:%f",scrollY);
    if (scrollView.contentOffset.y>=220) {
        self.sectionHeadView.hidden = NO;
        if (scrollView.contentOffset.y>= scrollY) {
            for (id obj in self.sectionHeadView.subviews) {
                if ([obj isKindOfClass:[UIButton class]]) {
                    XLog(@"obj:%@",obj);
                    UIButton *btn = (UIButton *)obj;
                    if (btn.tag == 0) {
                        [btn setTitleColor:kLabel153Color forState:UIControlStateNormal];
                        btn.titleLabel.font = [UIFont systemFontOfSize:14];
                    }else{
                        [btn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                        btn.titleLabel.font = [UIFont systemFontOfSize:16];
                    }
                }
            }
        }else {
            for (id obj in self.sectionHeadView.subviews) {
                if ([obj isKindOfClass:[UIButton class]]) {
                    XLog(@"obj:%@",obj);
                    UIButton *btn = (UIButton *)obj;
                    if (btn.tag == 0) {
                        [btn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                        btn.titleLabel.font = [UIFont systemFontOfSize:16];
                    }else{
                        [btn setTitleColor:kLabel153Color forState:UIControlStateNormal];
                        btn.titleLabel.font = [UIFont systemFontOfSize:14];
                    }
                }
            }
        }
    }else {
        self.sectionHeadView.hidden = YES;
    }
    
    NSIndexPath *visiblePath = [[self.tableView indexPathsForVisibleRows] firstObject];
    XLog(@"visiblePath:%ld",visiblePath.section);
    if (visiblePath.section >= 1) {
        self.contaceBtn.hidden = YES;
    }else {
        self.contaceBtn.hidden = NO;
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if(section == 0){
        return 1;
    }if(section == 1){
        return 6;
    }else if(section == 2){
        return 3;
    }else {
        return self.demandArray.count?self.demandArray.count+1:1;
        //        return 3;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    if (indexPath.section == 0) {
        DemandTheHallContentHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierCellHead forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.homeDemandModel = self.homeModel;
//        cell.collectBtn.selected = self.homeModel.collectStatus;
        cell.delegate = self;
        return cell;
    }else if (indexPath.section == 1) {
        if (indexPath.row== 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierWriteRequirementTitleCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.titleL.text = @"需求细节信息";
            return cell;
        }else {
            HomeServiceDetailsIntroductionContentTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierHomeServiceDetailsIntroductionContentTwoCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.indexPath = indexPath;
            
            //            cell.sendDemandHomeModel = self.homeModel;
            CellFrameModel *frameModel = [[CellFrameModel alloc]init];
            frameModel.indexPath = indexPath;
            frameModel.homeModel = self.homeModel;
            cell.frameModel = frameModel;
            return cell;
            
        }
    } if (indexPath.section == 2) {
        if (indexPath.row== 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierWriteRequirementTitleCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.titleL.text = @"需求详细描述";
            return cell;
        }else if (indexPath.row== 1) {
            ContentCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierContent forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.homeModel = self.homeModel;
            return cell;
        }else {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierWriteRequirementTitleCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }else {
        if (indexPath.row == 0) {
            WriteRequirementTitleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierWriteRequirementTitleCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.titleL.text = @"相似需求推荐";
            return cell;
        }else {
            DemandCell *cell = [tableView dequeueReusableCellWithIdentifier:identifierDemandCell forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
            cell.indexPath = indexPath;
            HomeModel *model = self.demandArray[indexPath.row-1];
            cell.homeModel = model;
            cell.collectShow = NO;
            //        cell.homeModel.showView = !self.homeModel.showView;
            return cell;
            
        }
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 233;
    }else if (indexPath.section == 1){
        if (indexPath.row== 0){
            return 40;
        }else {
            
            CellFrameModel *frameMode = [[CellFrameModel alloc]init];
            frameMode.homeModel = self.homeModel;
            XLog(@"cellHeight:%ld",frameMode.cellHeight);
            //            cell.sendDemandHomeModel = self.homeModel;
            CellFrameModel *frameModel = [[CellFrameModel alloc]init];
            frameModel.indexPath = indexPath;
            frameModel.homeModel = self.homeModel;
            //            cell.frameModel = frameModel;
            XLog(@"frameModel.cellHeight:%ld",(long)frameModel.cellHeight);
            return frameModel.cellHeight;
            
        }
    }else if (indexPath.section == 2){
        if (indexPath.row== 0){
            return 60;
        }else if (indexPath.row== 1){
            CGFloat cellHeight = [MCLabel getHeightByWidth:kVWidth-18*2 title:self.homeModel.represent font:13]*1.5;
            XLog(@"cellHeight:%f",cellHeight);
            return cellHeight;
        }else {
            return 25;
        }
    }else {
        if (indexPath.row== 0){
            return 60;
        }else {
            return 144;
        }
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 3 &&indexPath.row != 0) {
        DemandTheHallContentVC *homeServiceVC = [[DemandTheHallContentVC alloc]init];
        homeServiceVC.homeModel = self.demandArray[indexPath.row-1];
        //        XLog(@"demandArray:%@",homeServiceVC.demandArray);
        [self.navigationController pushViewController:homeServiceVC animated:YES];
        
    }
}
#pragma mark-代理:打电话
-(void)demandCell:(DemandCell *)demandCell withClickBtn:(UIButton *)clickBtn withIndexPath:(NSIndexPath *)indexPath withHomeModel:(HomeModel *)homeModel
{
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                HomeModel *model = self.demandArray[indexPath.row-1];
                model.show = clickBtn.selected;
                [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }else {
                [UIAlertViewWarningAccount showWarningAccount];
                [LogOutAccount presentOutAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
#pragma mark-立即联系
-(void)contactBtn
{
    if ([[UserDefaultsHelper readAutoLogIn] isEqualToString:@"NO"]) {
        [LogOutAccount presentOutAccount];
        [UIAlertViewWarningAccount showWarningAccount];
    }else if ([UserDefaultsHelper readAutoLogIn].length == 0) {
        [LogOutAccount presentOutAccount];
    }else {
        self.dict = @{
                      @"userId":[UserDefaultsHelper readUid],
                      @"token":[UserDefaultsHelper readToken]
                      };
        self.urlString = [NSString stringWithFormat:@"%@/user/checkToken",kUrl];
        [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSInteger status = [[responseObject objectForKey:@"status"] integerValue];
            if (status == 200) {
                [self choiceContactWay];
            }else {
                [UIAlertViewWarningAccount showWarningAccount];
                [LogOutAccount presentOutAccount];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
}
-(void)choiceContactWay
{
    YXAlertController *alertController = [YXAlertController alertControllerWithTitle:@"请选择联系方式" message:@"" style:YXAlertControllerStyleActionSheet];
    NSString *way = @"";
    if (self.homeModel.phone.length > 0) {
        way = [NSString stringWithFormat:@"手机号: %@",self.homeModel.phone];
        YXAlertAction *phone = [YXAlertAction actionWithTitle:way style:0 handler:^(YXAlertAction * _Nonnull action) {
            NSMutableString * callPhone= [[NSMutableString alloc] initWithFormat:@"tel:%@",self.homeModel.phone];
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone] options:@{} completionHandler:nil];
            } else {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
            }

            self.urlString = [NSString stringWithFormat:@"%@/relation/insertRelation",kUrl];
            NSString *ids = [NSString stringWithFormat:@"%ld",self.homeModel.id];
            self.dict = @{
                          @"uid":[UserDefaultsHelper readUid],
                          @"relationId":ids,
                          @"type":@"1",
                          @"token":[UserDefaultsHelper readToken]
                          };
            XLog(@"self.dict:%@",self.dict);
            [self.manager POST:self.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                XLog(@"responseObject:%@",responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                XLog(@"error:%@",error);
            }];
        }];
        [alertController addAction:phone];
    }
    if (self.homeModel.wechat.length > 0) {
        way = [NSString stringWithFormat:@"微信号: %@",self.homeModel.wechat];
        YXAlertAction *wecht = [YXAlertAction actionWithTitle:way style:0 handler:^(YXAlertAction * _Nonnull action) {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = self.homeModel.wechat;
            NSURL *url = [NSURL URLWithString:@"weixin://"];
            BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:url];
            if (canOpen) {
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"微信号已复制到剪切板"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [[UIApplication sharedApplication] openURL:url];
                    
                });
            }else{
                //        NSLog(@"未安装微信");
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"未安装微信"];
            }
        }];
        [alertController addAction:wecht];
    }
    if (self.homeModel.qq.length>0) {
        way = [NSString stringWithFormat:@"QQ号: %@",self.homeModel.qq];
        YXAlertAction *qq = [YXAlertAction actionWithTitle:way style:0 handler:^(YXAlertAction * _Nonnull action) {
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"mqq://"]]) {
                UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
                NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:@"mqq://im/chat?chat_type=wpa&uin=%@&version=1&src_type=web",self.homeModel.qq]];
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                [webView loadRequest:request];
                [self.view addSubview:webView];
            }else{
                XLog(@"对不起，您还未安装QQ");
                [WSProgressHUD showImage:[UIImage imageNamed:@""] status:@"未安装QQ"];
            }
        }];
        [alertController addAction:qq];
    }
    YXAlertAction *cancel = [YXAlertAction actionWithTitle:@"取消" style:1 handler:^(YXAlertAction * _Nonnull action) {
    }];
    [alertController layoutSettings];
    [alertController addAction:cancel];
    [alertController presentFromViewController:self animated:YES completion:nil];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, kSectionHeight)];
    headerView.backgroundColor = [UIColor whiteColor];
    if (section == 1) {
        for (int i = 0; i < 2; i++) {
            UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(kVWidth/2*i, 0, kVWidth/2, kSectionHeight)];
            [btn addTarget: self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = i;
            [headerView addSubview:btn];
            NSArray *titles = @[@"详情介绍",@"推荐"];
            [btn setTitle:titles[i] forState:UIControlStateNormal];
            if (i == 0) {
                [btn setTitleColor:kOrangeBg forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:16];
            }else {
                [btn setTitleColor:kLabel153Color forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:14];
            }
        }
        return headerView;
    }else {
        return nil;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return kSectionHeight;
    }else {
        return 0.1;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0,1)];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 3) {
        return 0;
    }else {
        return 0.1;
    }
}
@end
